<?php
namespace Home\Controller;
use Home\Model\UserModel;
use Think\Controller;
class BaseController extends Controller{
	public $_APPID ='';
	public $_AppSecret ='';
	public $_userid = '';
	public $_openid='';
	
    public function __construct(){
    	parent::__construct();
        $this->_APPID=C("APPID");
        $this->_AppSecret=C("AppSecret");
	 	$userModel = new UserModel();
		$sessionid = $_COOKIE['sessionid'];
    	if ($sessionid && $userItem = $userModel->getUserItem(array('sessionid'=>$sessionid))) {
         	$this->_userid = $userItem['id'];
            $this->_openid = $userItem['openid'];
            cookie('sessionid',$userItem['sessionid'],60*60*24*7);
         }else{
         	$this->_userid = '';
            $this->_openid = '';
            cookie('sessionid',null);
         }
    }
 	/**
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     */
    public function getToken()
    {
    	$appid =$this->_APPID;
    	$appsecret = $this->_AppSecret;
        if (S($appid)) {
            $access_token = S($appid);
        }else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            S($appid, $access_token, 720);
        }
        return $access_token;
    }
    
	/**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }
    
    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
	/**
	 * cookie设置
	 * @param $var 设置的cookie名
	 * @param $value 设置的cookie值
	 * @param $life 设置的过期时间：为整型，单位秒 如60表示60秒后过期
	 * @param $path 设置的cookie作用路径
	 * @param $domain 设置的cookie作用域名
	 */
	public static function ssetcookie($array, $life=0, $path = '/') {
		$_cookName_ary = array_keys($array);
		for($i = 0; $i < count($array); $i++) {
			//echo $_cookName_ary[$i].'='.$array[$_cookName_ary[$i]].'<br>';
			$httpOnly = false;
			setcookie($_cookName_ary[$i], $array[$_cookName_ary[$i]], $life?(time()+$life):0, $path);
		}
	}

	/**
	 * jssdk函数
	 * @param unknown $appId
	 * @param unknown $appSecret
	 */
	protected function getSignPackage() {
	    $jsapiTicket = $this->getJsApiTicket();
	    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	    $timestamp = time();
	    $nonceStr = $this->createNonceStr();
	
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	
	    $signature = sha1($string);
	    $signPackage = array(
	        "appId"     => $this->_APPID,
	        "nonceStr"  => $nonceStr,
	        "timestamp" => $timestamp,
	        "url"       => $url,
	        "signature" => $signature,
	        "rawString" => $string
	    );
	    return $signPackage;
	}
	
	protected function createNonceStr($length = 16) {
	    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $str = "";
	    for ($i = 0; $i < $length; $i++) {
	        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	    }
	    return $str;
	}
	
	protected function getJsApiTicket() {
	    // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
	    $data = json_decode(file_get_contents("jsapi_ticket.json"));
	    if ($data->expire_time < time()) {
	        $accessToken = $this->getToken();
	        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
	        $res = json_decode($this->request_get($url));
	        $ticket = $res->ticket;
	        if ($ticket) {
	            $data->expire_time = time() + 7000;
	            $data->jsapi_ticket = $ticket;
	            $fp = fopen("jsapi_ticket.json", "w");
	            fwrite($fp, json_encode($data));
	            fclose($fp);
	        }
	    } else {
	        $ticket = $data->jsapi_ticket;
	    }
	    return $ticket;
	}
	
	protected function getAccessToken() {
	    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
	    $data = json_decode(file_get_contents("access_token.json"));
	    if ($data->expire_time < time()) {
	        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->_APPID&secret=$this->_AppSecret";
	        $res = json_decode($this->request_get($url));
	        $access_token = $res->access_token;
	        if ($access_token) {
	            $data->expire_time = time() + 7000;
	            $data->access_token = $access_token;
	            $fp = fopen("access_token.json", "w");
	            fwrite($fp, json_encode($data));
	            fclose($fp);
	        }
	    } else {
	        $access_token = $data->access_token;
	    }
	    return $access_token;
	}

	protected function getAccessTokenDown(){
	    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->_APPID&secret=$this->_AppSecret";
	    $res = json_decode($this->request_get($url));
	    $access_token = $res->access_token;
	    return $access_token;
	}
}

